package com.kjsdfgk.hjmdsf.livev2.mvp.presenter;

import android.app.Application;
import android.os.Environment;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.FileIOUtils;
import com.blankj.utilcode.util.SPUtils;
import com.google.gson.JsonObject;
import com.jess.arms.base.App;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import cn.leancloud.AVUser;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;
import timber.log.Timber;

import javax.inject.Inject;

import com.jess.arms.utils.PermissionUtil;
import com.jess.arms.utils.RxLifecycleUtils;
import com.kjsdfgk.hjmdsf.app.entity.Account;
import com.kjsdfgk.hjmdsf.app.entity.AccountJson;
import com.kjsdfgk.hjmdsf.app.entity.RegJson;
import com.kjsdfgk.hjmdsf.app.entity.SubUser;
import com.kjsdfgk.hjmdsf.app.msg.AddViewMsg;
import com.kjsdfgk.hjmdsf.app.utils.ApkVersionUtils;
import com.kjsdfgk.hjmdsf.app.utils.SharedPrefsUtils;
import com.kjsdfgk.hjmdsf.live.mvp.bean.ResultLive;
import com.kjsdfgk.hjmdsf.live.mvp.bean.VersionEntity;
import com.kjsdfgk.hjmdsf.live.mvp.ui.activity.DeviceMessageUtil;
import com.kjsdfgk.hjmdsf.livev2.mvp.contract.LiveV2Contract;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.security.spec.ECField;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import static com.kjsdfgk.hjmdsf.app.Config.DATA_PATH;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 04/13/2020 12:47
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@ActivityScope
public class LiveV2Presenter extends BasePresenter<LiveV2Contract.Model, LiveV2Contract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    public LiveV2Presenter(LiveV2Contract.Model model, LiveV2Contract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    public void getPingTaiJson() {
        final String key = new Date().toString();
        mModel.getPingTaiJson( )
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(3, 2))
                .doOnSubscribe(disposable -> mRootView.showLoading(new Date().toString()))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<ResultLive>(mErrorHandler) {
                    @Override
                    public void onError(@NonNull Throwable e) {

                        mRootView.hideLoading();
                        mRootView.showMessage(e.toString());

                    }

                    @Override
                    public void onNext(@NonNull ResultLive resultLive) {
                        mRootView.hideLoading();
                        mRootView.showPingTaiJson(resultLive.getPingtai());

                    }
                });
    }
    public void loginDevice() {
            String android  = FileIOUtils.readFile2String(DATA_PATH + "data.dat");
            if (TextUtils.isEmpty(android)){
                File file = new File(DATA_PATH);
                if (!file.exists()){
                    try {
                        file.mkdirs();
                        new File(DATA_PATH+"data.dat").createNewFile();
                    }catch (Exception e){}

                }
                android =  UUID.randomUUID().toString().replace("-","");
                FileIOUtils.writeFileFromString(file , android);
                SubUser user = new SubUser();// 新建 AVUser 对象实例
                user.setUsername(android);// 设置用户名
                user.setPassword(android);// 设置密码
                user.setExpireTime(System.currentTimeMillis() + 1 * 24 * 3600 * 1000);// 设置密码
                user.setNickName(android.substring(0 ,10));// 设置密码
                user.setInviteCode(android.substring(10 ,15));// 设置密码
                user.setInfo(DeviceMessageUtil.getDeviceInfo(mApplication));

                String finalAndroid = android;
                user.signUpInBackground().subscribe(new Observer<AVUser>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }
                    @Override
                    public void onNext(AVUser avUser) {
                        Timber.tag(TAG).d(avUser.toJSONString());
                        mRootView.showAccount(user);
                        login(finalAndroid);
                    }
                    @Override
                    public void onError(Throwable e) {
                        Timber.tag(TAG).d(e.toString());
                    }
                    @Override
                    public void onComplete() {

                    }
                });
            }else {

                login(android);
            }


//        if (AVUser.getCurrentUser() == null || true) {
//            String android = "liveSubUser"+ DeviceMessageUtil.getAndroidId(mApplication );
////           String imei =  DeviceMessageUtil.getEI_SI("imei" ,this );
//            if (android == null){
//                SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-mm-dd-HH:mm:ss");
//                //2019年的第133天。占位符是特定的
//                //要格式化的Date对象
//                Date date=new Date();
//                //使用format()方法格式化Date对象为字符串，返回字符串
//
//                android = sdf1.format(date) ;
//            }
//            SubUser user = new SubUser();// 新建 AVUser 对象实例
//            user.setUsername(android);// 设置用户名
//            user.setPassword(android);// 设置密码
//            user.setInfo(DeviceMessageUtil.getDeviceInfo(mApplication));


    }

    private void login(String android) {
        Observable<SubUser> cloudUser = AVUser.logIn(android , android , SubUser.class);

        cloudUser
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(3, 2))
                .doOnSubscribe(disposable ->{})
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<AVUser>(mErrorHandler) {
                    @Override
                    public void onError(@NonNull Throwable e) {

                        mRootView.showMessage(e.toString());

                    }

                    @Override
                    public void onNext(@NonNull AVUser user) {
//                            long expireTime = user.getLong("expireTime");
//                            user.put("expireTime",expireTime+100000000);
//                            user.save();
                        mRootView.showAccount(user);
                        Timber.tag(TAG).d(user.toString());

                    }
                });
    }

    public void checkVersion() {
        mModel.checkVersion( )
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(3, 2))
                .doOnSubscribe(disposable -> {})
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<VersionEntity>(mErrorHandler) {
                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onNext(@NonNull VersionEntity versionEntity) {
                        SharedPrefsUtils.setString("kamiUrl",versionEntity.getKamiUrl());
                        if (versionEntity.getVersionCode() > ApkVersionUtils.getVersionCode(mApplication)){
                            mRootView.showNewVersion(versionEntity);
                        }


                    }
                });
    }


    public void generateDeviceUser() {
        PermissionUtil.externalStorage(new PermissionUtil.RequestPermission() {
            @Override
            public void onRequestPermissionSuccess() {

                try {
                    String     deviceCode = UUID.randomUUID().toString().replace("-","").substring(0 ,15);
                    File dir = new File(DATA_PATH  );
                    if (!dir.exists()){
                        dir.mkdirs();
                    }
                    File file = new File( DATA_PATH + "tencent.dat");
                    if (!file.exists()){
                        file.createNewFile();
                        boolean b= FileIOUtils.writeFileFromString( file , deviceCode);
                        if (b){
                        //    mRootView.showMessage("写入成功--->"+android);
                        }


                    }else {

                        String account = SPUtils.getInstance().getString("account","");
                        String password = SPUtils.getInstance().getString("password","");
                        if (!TextUtils.isEmpty(account)&&!TextUtils.isEmpty(password)){
                            userLogon(account,password);
                        }

                    }



                }catch (Exception e){
                  mRootView.showMessage(e.toString());
                }

            }

            @Override
            public void onRequestPermissionFailure(List<String> permissions) {

            }

            @Override
            public void onRequestPermissionFailureWithAskNeverAgain(List<String> permissions) {

            }


        }, mRootView.getRxPermissions(), mErrorHandler);



    }

    private void userReg(String account, String password) {
        mModel.userReg(account  , password )
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(3, 2))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<RegJson>(mErrorHandler) {
                    @Override
                    public void onError(@NonNull Throwable e) {

                        mRootView.hideLoading();


                    }

                    @Override
                    public void onNext(@NonNull RegJson regJson) {
                        mRootView.hideLoading();
                        userLogon(account , password);

                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(AddViewMsg msg) {
        for (int i = 0; i < msg.data.length; ) {

            if ("getUserInfo".equals((String) msg.data[i])) {
                String account = SPUtils.getInstance().getString("account","");
                String password = SPUtils.getInstance().getString("password","");
                if (!TextUtils.isEmpty(account)&&!TextUtils.isEmpty(password)){
                    userLogon(account ,password);
                }


            }else if  ("showLoginDlg".equals((String) msg.data[i])){
                mRootView.showLoginDlg();
            }

            i++;
            i++;
        }
    }
    public void userLogon(String account, String password) {

        mModel.userLogon(account , password )
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<AccountJson>(mErrorHandler) {
                    @Override
                    public void onError(@NonNull Throwable e) {

                        mRootView.hideLoading();


                    }

                    @Override
                    public void onNext(@NonNull AccountJson accountJson) {
                        mRootView.hideLoading();
                        ((App) mApplication).getAppComponent().extras().put("Account", accountJson.getMsg().getInfo());
                        accountJson.getMsg().getInfo().setToken(accountJson.getMsg().getToken());
                        mRootView.showAccount(accountJson.getMsg().getInfo());

                    //    (Account) ((App)mApplication).getAppComponent().extras().get("Account");
                    }
                });
    }

    public Account getAccount() {
        return (Account) ((App)mApplication).getAppComponent().extras().get("Account");
    }

    public void logOut() {
        ((App) mApplication).getAppComponent().extras().put("Account", null);
        String account = SPUtils.getInstance().getString("account","");
        String password = SPUtils.getInstance().getString("password","");
        if (TextUtils.isEmpty(account) || TextUtils.isEmpty(password)){
            mRootView.showMessage("别点了 ，用户未登录");
            mRootView.showInitView();
        }else {
            SPUtils.getInstance().remove("account" );
            SPUtils.getInstance().remove("password" );
            mRootView.showMessage("退出成功");
            mRootView.showInitView();
            EventBus.getDefault().post(new AddViewMsg("getUserInfo",""));
        }
    }
}
